import numpy as np
import pandas as pd

# 3sigma（超过3sigma范围为异常点）
def three_sigma(df):
    mean = df.y.mean()
    std = df.y.std()
    upper_limit = mean+3*std
    lower_limit = mean-3*std
    df['anomaly']=df.y.apply(lambda x: 1 if (x > upper_limit)
                              or (x < lower_limit) else 0)
    return df

'''
对外调用接口;
提供给外部其他Python文件调用接口.
'''
def three_sigma_route(data,url):
    if url:
        data1 = pd.read_excel(url)
    else:
        data1 = data

    data1.columns = ['y']
    df1 = three_sigma(data1.copy())
    label1 = np.array(df1['anomaly']).reshape(-1,1)
    label = label1.tolist()
    return label

if __name__ =="__main__":
    # 读取文件
    url = 'Sigma_data.xlsx'
    data = pd.read_excel('Sigma_data.xlsx')
    label = three_sigma_route(data,url)

    # 输出label,label=0为正常点，label=1为异常点
    print('lable:', label)
